import { Injectable, Inject, HttpException, HttpStatus } from '@nestjs/common';
import {
  InjectRepository,
  InjectConnection,
  InjectEntityManager,
} from '@nestjs/typeorm';
import { Repository, getConnection } from 'typeorm';
import { ApiErrorCode } from '../../common/enums/api-error-code.enum';
import {
  Response,
  ResponseParam,
  CurrentError,
} from '../../common/enums/response';
import { Caller } from 'src/entities/caller.entity';
import { PgaeDto } from './caller.dto';

@Injectable()
export class CallerService {
  @InjectRepository(Caller) private readonly caller: Repository<Caller>;
  constructor() {}

  public async created(param: any): Promise<object> {
    try {
      param.p_created_at = new Date();
      await this.caller.save(param);
      let responseParam: ResponseParam = {
        message: ApiErrorCode.LACK_SET_SUCCESS,
        data: null,
      };
      return Response(responseParam);
    } catch (error) {
      return CurrentError.LACK_SET_FAIL;
    }
  }

  public async put(id: number, param: any): Promise<object> {
    try {
      delete param.id;
      param.p_updated_at = new Date();
      await this.caller.update(
        { id },
        {
          isCall: param.isCall,
          phone: param.phone,
          name: param.name,
          isSms: param.isSms,
        },
      );
      let responseParam: ResponseParam = {
        message: ApiErrorCode.LACK_UPDATE_SUCCESS,
        data: null,
      };
      return Response(responseParam);
    } catch (error) {
      return CurrentError.LACK_UPDATE_FAIL;
    }
  }

  public async delete(id: number): Promise<object> {
    try {
      await this.caller.delete({ id });
      let responseParam: ResponseParam = {
        message: ApiErrorCode.LACK_DEL_SUCCESS,
        data: null,
      };
      return Response(responseParam);
    } catch (error) {
      return CurrentError.LACK_DEL_FAIL;
    }
  }

  public async getList(param: PgaeDto) {
    const list = await this.caller
      .createQueryBuilder()
      .where('deviceId = :deviceId', { deviceId: param.deviceId })
      .orderBy('creatTime', 'DESC')
      .skip((param.page - 1) * param.pageSize)
      .take(param.pageSize)
      .getManyAndCount();
    let responseParam: ResponseParam = {
      message: ApiErrorCode.LACK_GET_SUCCESS,
      data: list[0],
      count: list[1],
    };
    return Response(responseParam);
  }
}
